<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="结算明细"
                    name="billingDetails"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="保证金"
                    name="margin"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        :rules="formDataRules"
                                        ref="formDataRef"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="结算编号">
                                                    {{ formData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="结算日期">
                                                    {{ formData.billDate }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="合同编号"
                                                    prop="contractNo"
                                                >
                                                    {{ formData.contractNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="结算单位"
                                                    prop="settleOrgName"
                                                >
                                                    {{ formData.settleOrgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="发票编号"
                                                    prop="invoice"
                                                >
                                                    {{ formData.invoice }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="机构"
                                                    prop="orgName"
                                                >
                                                    {{ formData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税率%"
                                                    prop="taxRate"
                                                >
                                                    {{ formData.taxRate }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税额(元)"
                                                    prop="taxAmount"
                                                >
                                                    {{ formData.taxAmount }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <!-- 从结算明细中获取金额的汇总数据 -->
                                                <el-form-item
                                                    label="不含税金额(元)"
                                                    prop="amountExcludingTax"
                                                >
                                                    {{
                                                        formData.amountExcludingTax
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <!-- 税额、不含税金额合计，不可修改 -->
                                                <el-form-item
                                                    label="税价合计(元)"
                                                    prop="totalTaxPrice"
                                                >
                                                    {{ formData.totalTaxPrice }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <!-- 自动获取该结算单位已经结算的金额，即税价合计的累计值，截止本期末 -->
                                                <el-form-item
                                                    label="累计结算金额"
                                                    prop="cumulativeSettleAmount"
                                                >
                                                    {{
                                                        formData.cumulativeSettleAmount
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col
                                                :span="12"
                                                v-if="formData.contractNo"
                                            >
                                                <el-form-item label="终期结算">
                                                    <el-checkbox
                                                        v-model="
                                                            formData.finalSettlement
                                                        "
                                                        label=""
                                                        style="
                                                            margin-right: 10px;
                                                        "
                                                        disabled
                                                    ></el-checkbox>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row v-if="formData.contractNo">
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="冲预付款"
                                                    prop="rushAdvanceCharge"
                                                >
                                                    <el-checkbox
                                                        v-model="
                                                            formData.rushAdvanceCharge
                                                        "
                                                        label=""
                                                        style="
                                                            margin-right: 10px;
                                                        "
                                                        disabled
                                                    ></el-checkbox>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="冲预付款金额(元)"
                                                    :prop="
                                                        formData.rushAdvanceCharge
                                                            ? 'rushAdvanceChargePrice'
                                                            : 'rushAdvanceChargePrices'
                                                    "
                                                >
                                                    {{
                                                        formData.rushAdvanceChargePrice
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="币种"
                                                    prop="currencyId"
                                                >
                                                    {{ formData.currency }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="传输财务共享"
                                                    prop="share"
                                                >
                                                    {{ formData.share }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币"
                                                    prop="baseCurName"
                                                >
                                                    {{ formData.baseCurName }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="人民币汇率"
                                                >
                                                    {{ formData.rmbRate }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币汇率"
                                                    prop="baseCurRate"
                                                >
                                                    {{ formData.baseCurRate }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="状态">
                                                    {{
                                                        showState(
                                                            formData.state
                                                        )
                                                    }}
                                                    <!-- 草稿/审核中/已审核/已关闭/已作废 -->
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <!-- <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="冲预付款金额(本位币)"
                                                >
                                                    {{
                                                        formData.baseCurPaymentPrice
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税价合计(本位币)"
                                                >
                                                    {{
                                                        formData.baseCurTotalTaxPrice
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row> -->

                                        <el-row>
                                            <el-form-item label="备注">
                                                {{ formData.remarks }}
                                            </el-form-item>
                                        </el-row>
                                        <el-row v-show='formData.redBillState !== -1'>
                                            <el-form-item label="冲红单"
                                                ><span
                                                    :style="redBillStateStyle"
                                                    >{{ redBillStateFun }}</span
                                                ></el-form-item
                                            >
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item label="作废人：">
                                                    <span>{{
                                                        formData.nullifyCreator
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废原因："
                                                >
                                                    <span>{{
                                                        formData.nullifyReason
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废说明："
                                                >
                                                    <span>{{
                                                        formData.nullifyDesciption
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废时间："
                                                >
                                                    <span>{{
                                                        formData.nullifyCreated
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- 结算明细 -->
                    <div id="billingDetailsCon" class="con">
                        <div class="tabs-title" id="billingDetails">
                            结算明细
                        </div>
                        <div class="e-table">
                            <div
                                class="errorMsg"
                                v-if="errorBillingMsg.length > 0"
                            >
                                <span>
                                    {{ errorBillingMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="settlementData"
                                ref='settlementTable'
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClassName"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': settlementData, '_this': this, 'ref': 'settlementTable' }"
                            >
                                <el-table-column
                                    prop="detailedName"
                                    label="名称"
                                    min-width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    min-width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="departurePlace"
                                    label="出发地"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="目的地"
                                    prop="destination"
                                >
                                </el-table-column>
                                <el-table-column label="数量" prop="amount">
                                </el-table-column>
                                <el-table-column
                                    label="单价(元)"
                                    width="100"
                                    prop="price"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="金额(元)"
                                    width="120"
                                    prop="sum"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <!-- 保证金 -->
                    <div id="marginCon" class="con">
                        <div class="tabs-title" id="margin">保证金</div>
                        <Margin
                            :isRedSingle="isRedSingle"
                            :billid="billid"
                            :number="fhObj"
                            ref="marginRef"
                            :isDtl="true"
                        ></Margin>
                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="billid"
                            bucketName="facilitysettle"
                            v-if="objFlag.flag5"
                            :isView='true'
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <EquipmentBillingHistory
                            :billType="3021"
                            :billId="billid"
                            @historyTableHeight="historyTableHeight"
                        />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <!-- <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="
                    formData.state == 1 ||
                    formData.state == 9 ||
                    formData.state == 2
                "
                >打印</el-button
            > -->
            <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="formData.state == 2 && !formData.sourceId"
                @click="redSingle"
                >冲红单</el-button
            >
            <exaButtons :auditState="auditState" @exas="exas" v-if='formData.state !== 5' :state='formData.state' :founderId='formData.founderId' :multiple="formData.state === 1 || formData.state === 2" :commandList='commandList'></exaButtons>

            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapState, mapMutations } from 'vuex'
import AttachComp from '@/components/common/attachIndex'
import EquipmentBillingHistory from '@/pages/settlementManagement/equipmentBilling/EquipmentBillingHistory'
import Margin from '@/pages/settlementManagement/equipmentBilling/Margin'
import { showLoading, hideLoading, openAppClient, webprintReport, numToChinese } from '@/utils/common'
import request from '@/api/settlementManagement/equipmentBilling/contractOfCarriage'
import publics from '@/api/settlementManagement/equipmentBilling/public'
import exaButtons from '@/components/common/exaButtons'

export default {
    components: {
        AttachComp,
        EquipmentBillingHistory,
        exaButtons,
        Margin
    },
    data () {
        return {
            tabsName: 'baseInfo',
            clickId: 'baseInfo',
            //表单数据
            formData: {
                amountExcludingTax: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurPaymentPrice: 0,
                baseCurRate: 0,
                baseCurTotalPrice: 0,
                baseCurTotalTaxPrice: 0,
                billDate: '',
                billId: '',
                billNo: '',
                contractId: '',
                contractName: '',
                contractNo: '',
                cumulativeSettleAmount: 0,
                currency: '',
                currencyId: '',
                evaluate: 0,
                evaluateGrade: '',
                finalSettlement: 0,
                founderId: '',
                founderName: '',
                invoice: '',
                isRed: false,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDesciption: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                redBillState: 0,
                remarks: '',
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbSumTotalPrice: 0,
                rushAdvanceCharge: 0,
                rushAdvanceChargePrice: 0,
                rushPinAmount: '',
                settleOrgId: '',
                settleOrgName: '',
                share: '',
                sourceId: '',
                sourceNumber: '',
                state: 0,
                taxAmount: 0,
                taxRate: 0,
                totalTaxPrice: 0,
                workId: ''
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转

            formDataRules: {
                taxRate: [
                    { required: true, message: '请输入税率', trigger: 'change' }
                ],
                contractNo: [
                    {
                        required: true,
                        message: '请选择合同编号',
                        trigger: 'blur'
                    }
                ],
                settleOrgName: [
                    {
                        required: true,
                        message: '请获取结算单位',
                        trigger: 'blur'
                    }
                ],
                invoice: [
                    {
                        required: true,
                        message: '请填写发票号',
                        trigger: 'blur'
                    }
                ],
                taxAmount: [
                    {
                        required: true,
                        message: '请输入税额(元)',
                        trigger: 'blur'
                    }
                ],
                rushAdvanceChargePrice: [
                    {
                        required: true,
                        message: '请填写冲预付款金额(元)',
                        trigger: 'blur'
                    }
                ],
                amountExcludingTax: [
                    {
                        required: true,
                        message: '请输入不含税金额(元)',
                        trigger: 'blur'
                    }
                ],
                totalTaxPrice: [
                    {
                        required: true,
                        message: '请输入税价合计(元)',
                        trigger: 'blur'
                    }
                ],

                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'blur' }
                ],

                baseCurName: [
                    {
                        required: true,
                        message: '请选择本位币',
                        trigger: 'blur'
                    }
                ],
                baseCurRate: [
                    {
                        required: true,
                        message: '请选择本位币',
                        trigger: 'blur'
                    }
                ]
            },
            isRedSingle: false,
            redFormData: null,
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            isBaseCurRate: true,
            settlementData: [], // 结算明细
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            objFlag: {
                flag5: false
            },
            MouseEnterId: null,
            MouseEnterIdF: null,
            auditState: {},
            auditParams: {
                billId: '',
                billType: 3021,
                freeNextUnitIndex: null,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            },
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '3021',
                nullifyDescription: '',
                nullifyReason: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            errorList: [], //控制导航栏感叹号的显示
            errorBillingMsg: [], // 结算明细
            errorSuspendedMsg: [], // 暂扣保证金
            errorReturnMsg: [], // 返还保证金
            marginTabs: 'withholdingSecurityDeposit',
            childTabClass: '',
            billid: '',
            suspendedData: [], // 暂扣保证金数据
            returnData: [], // 返还保证金数据
            fhObj: {
                type: '3',
                contractId: ''
            },
            isTotalPrice: false, // 冲预付款是否显示输入框
            historyData: [],
            commandList: [
                { key: 1, value: '运输合同结算单' },
                { key: 2, value: '运输合同保证金暂扣/返还单' }
            ]
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        //状态
        //  showState () {
        //     return param => {
        //         const state = this.$store.state.equip.equipData.settleState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 20 - this.lastConHeight
        },

        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' (newData, oldData) {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isBaseCurRate = true
                this.formData.baseCurRate = 1
            } else {
                this.isBaseCurRate = false
                if (oldData != '') {
                    this.formData.baseCurRate = null
                }
            }
        },

        // 冲预付款勾选中,冲预付款金额必填
        'formData.rushAdvanceCharge' () {
            if (!this.formData.rushAdvanceCharge) {
                this.$refs.formDataRef.clearValidate('rushAdvanceChargePrice')
                this.formData.rushAdvanceChargePrice = ''
            }
        },

        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        },
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.auditParams.billId = this.$route.query.billid
        this.getBasic() // 获取基本信息
        this.getSettlement() // 结算明细
        this.getUnitInfo() // 获取按钮状态
        this.getAttach() // 获取附件列表
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'billingDetails',
            'margin',
            'attach',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop + 20
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 50 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        if (this.$route.query.name) {
            this.scorllDtl()
        }
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setSelectedInfo']),
        //如果是新增后,直接跳转到编辑页的情况需要跳转到第二个标签
        scorllDtl () {
            setTimeout(() => {
                //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                let obj = {
                    name: this.$route.query.name
                }
                this.tabsName = this.$route.query.name
                this.onChangeTab(obj)
            }, 200)
        },

        // 进入页面获取基本信息
        async getBasic () {
            let data = await request.getBasicInfo(this.billid)
            this.redFormData = this._.cloneDeep(data)
            this.fhObj.contractId = data.contractId // 合同id
            data.redBillState == 3
                ? (this.isRedSingle = true)
                : (this.isRedSingle = false)
            this.formData = data
            this.formData.rushAdvanceCharge
                ? (this.formData.rushAdvanceCharge = true)
                : (this.formData.rushAdvanceCharge = false)
            // 税额 = 不含税金额*税率
            this.$watch('formData.amountExcludingTax', () => {
                this.formData.taxAmount =
                    (+this.formData.amountExcludingTax * (+this.formData.taxRate / 100)).toFixed(2)
            })
            // 税额 = 不含税金额*税率
            this.$watch('formData.taxRate', () => {
                this.formData.taxAmount =
                    (+this.formData.amountExcludingTax * (+this.formData.taxRate / 100)).toFixed(2)
            })
            // 监听税额, 税价合计 = 税额 + 不含税金额
            this.$watch('formData.taxAmount', () => {
                this.formData.totalTaxPrice =
                    +this.formData.taxAmount +
                    +this.formData.amountExcludingTax
            })
            // 税价合计(本位币) = 税价合计(元) * 本位币汇率
            this.$watch('formData.totalTaxPrice', () => {
                this.formData.baseCurTotalTaxPrice = (
                    +this.formData.totalTaxPrice * +this.formData.baseCurRate
                ).toFixed(2)
            })
            // 冲预付款金额(本位币)
            this.$watch('formData.rushAdvanceChargePrice', () => {
                this.formData.baseCurPaymentPrice = (
                    +this.formData.rushAdvanceChargePrice *
                    +this.formData.baseCurRate
                ).toFixed(2)
            })
            // 终期结算
            this.$watch('formData.finalSettlement', () => {
                // 勾选终期结算后,带出全部未冲销预付金额并且不能修改
                if (this.formData.finalSettlement) {
                    // 如果未冲销的预付金额有,才勾选上冲预付款
                    if (this.formData.rushPinAmount) {
                        this.formData.rushAdvanceCharge = true
                    } else {
                        this.formData.rushAdvanceCharge = false
                    }
                    this.formData.rushAdvanceChargePrice =
                        this.formData.rushPinAmount
                    this.isTotalPrice = false
                } else {
                    this.isTotalPrice = true
                }
            })
        },

        // 基本信息-合同编号
        async contractNoClick () {
            let res = await request.contractNoClick(this.formData.contractId)
            let data = res[0]
            this.formData.contractId = data.contractId // 合同id
            this.formData.contractNo = data.contractNumber // 合同编号
            this.formData.settleOrgId = data.secondPartyId // 结算单位
            this.formData.settleOrgName = data.secondPartyName // 结算单位
            this.formData.taxRate = data.taxRate // 税率,当选择合同的时候，税率从合同带入
            this.fhObj.contractId = data.contractId // 合同id
            this.redemptionFun(data.contractId)
        },
        // 获取可冲预付款金额
        async redemptionFun (contractId) {
            let res = await publics.redemptionFun(contractId, this.orgId) //未冲预付款金额
            if (typeof res === 'object') {
                this.formData.rushPinAmount = 0
            } else {
                this.formData.rushPinAmount = res
            }
        },

        // 当币种切换时,获取人民币汇率
        async currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种名称
            let res = await publics.getRmbRate({
                //获取机构下某币种的人民币汇率
                currency: val,
                orgId: this.userInfo.orgInfo.orgId
            })
            this.formData.rmbRate = res.rate
        },
        // 本位币汇率不能为0
        baseCurRateBlur () {
            if (this.formData.baseCurRate == 0) {
                this.formData.baseCurRate = null
            }
            // 预付款金额(本位币)
            this.formData.baseCurPaymentPrice = (
                +this.formData.rushAdvanceChargePrice *
                +this.formData.baseCurRate
            ).toFixed(2)
            // 税价合计(本位币)
            this.formData.baseCurTotalTaxPrice = (
                +this.formData.totalTaxPrice * +this.formData.baseCurRate
            ).toFixed(2)
        },

        // ---------------------------结算明细 ------------------------
        // 获取结算明细表格数据
        async getSettlement () {
            this.settlementData = await request.getSettlement(this.billid)
        },
        // 选择设备
        async selectDevice () {
            let ids = this.settlementData.map(item => {
                if (item.changeType !== -1) {
                    return item.dtlId
                }
            })
            let data = await request.selectDevice(
                this.formData.contractId,
                ids
            )
            // this.setSelectedInfo(data)
            // openAppClient('/showSelectedData', '选择结果')

            let arr = []
            arr = data.map(item => {
                return {
                    amount: item.quantity, // 数量
                    changeType: 1,
                    departurePlace: item.placeOfDeparture, // 出发地
                    destination: item.destination, // 目的地
                    detailedName: item.materialName, // 名称
                    dtlId: item.detailedId, // 弹窗明细id
                    isRed: '', // 是否红单
                    price: item.unitPrice, // 单价
                    sum: item.amount, // 金额
                    transportContractSettleDtlId: '', // 主键id
                    transportContractSettleId: this.billid, // 运输合同结算id
                    unit: item.unit // 计量单位
                }
            })
            // 将不同的设备添加进入表格
            arr.forEach(item => {
                const isPush = this.settlementData.every(
                    i => i.dtlId !== item.dtlId
                )
                if (isPush) {
                    this.settlementData.push(item)
                } else {
                    const newArr = this.settlementData.filter(
                        itm => itm.dtlId === item.dtlId
                    )
                    const indirectPush = newArr.some(m => m.changeType !== -1)
                    if (!indirectPush) {
                        this.settlementData.push(item)
                    }
                }
            })
            this.formData.amountExcludingTax = this.settlementData.reduce(
                (prev, c) => (prev += +c.sum || 0),
                0
            )
        },
        sumBlur (row) {
            if (row.changeType === 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (row.amount && row.sum) {
                // 单价 = 金额/数量
                row.price = (+row.sum / +row.amount).toFixed(2)
            }
            this.formData.amountExcludingTax = this.settlementData.reduce(
                (prev, c) => (prev += +c.sum || 0),
                0
            )
        },

        // 结算明细单条删除
        settlementDelete (row) {
            row.changeType = -1
            row.sum = 0
            this.formData.amountExcludingTax = this.settlementData.reduce(
                (prev, c) => (prev += +c.sum || 0),
                0
            )
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },

        // ----------------------在点击下面几个按钮前,需要做前置判断------------
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x => x === name)
            if (index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 设置结算明细有错误时在表格上面显示的错误信息
        setErrorBillingMsg (msg) {
            let index = this.errorBillingMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorBillingMsg.push(msg)
            }
        },

        // 设置保证金-暂扣保证金有错误时在表格上面显示的错误信息
        setErrorSuspendedMsg (msg) {
            let index = this.errorSuspendedMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorSuspendedMsg.push(msg)
            }
        },
        // 设置保证金-返还保证金有错误时在表格上面显示的错误信息
        setErrorReturnMsg (msg) {
            let index = this.errorReturnMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorReturnMsg.push(msg)
            }
        },
        // 点击左边的Tab标签
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },

        // 保存基本信息
        basicInfoSave () {
            return new Promise((resolve, reject) => {
                this.$refs.formDataRef.validate(valid => {
                    if (valid) {
                        if (this.formData.redBillState == 3) {
                            this.redFormData.remarks = this.formData.remarks
                        }
                        request
                            .basicInfoSave(
                                this.formData.redBillState == 3
                                    ? this.redFormData
                                    : this.formData
                            )
                            .then(() => {
                                this.clearError('baseInfo')
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                            })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },
        // 保存结算明细
        settlementSave () {
            this.errorBillingMsg = []
            return new Promise((resolve, reject) => {
                this.settlementData.forEach(item => {
                    // !item.detailedName
                    //     ? this.setErrorBillingMsg('请填写名称')
                    //     : ''
                    !item.unit ? this.setErrorBillingMsg('请填写计量单位') : ''
                    // !item.departurePlace
                    //     ? this.setErrorBillingMsg('请填写出发地')
                    //     : ''
                    // !item.destination
                    //     ? this.setErrorBillingMsg('请填写目的地')
                    //     : ''

                    // !item.amount
                    //     ? this.setErrorBillingMsg('请填写数量')
                    //     : ''
                    // !item.price
                    //     ? this.setErrorBillingMsg('请填写单价')
                    //     : ''
                    // !item.sum
                    //     ? this.setErrorBillingMsg('请填写金额')
                    //     : ''
                })
                if (this.errorBillingMsg.length > 0) {
                    this.setError('billingDetails')
                    reject('结算明细错误')
                    return
                } else {
                    // this.setSelectedInfo(this.settlementData)
                    // openAppClient('/showSelectedData', '选择结果')
                    request
                        .settlementSave(this.settlementData)
                        .then(() => {
                            this.clearError('billingDetails')
                            resolve()
                        })
                        .catch(err => {
                            this.errorBillingMsg[0] = err.message
                            this.setError('billingDetails')
                            reject(err)
                            // alert(err.message)
                        })
                }
            })
        },

        // 保证金保存
        async marginSave () {
            try {
                await publics.marginSave({
                    facilityBondList: this.$refs.marginRef.suspendedData,
                    facilityReturnBondList: this.$refs.marginRef.returnData
                })
                this.clearError('margin')
            } catch (err) {
                this.setError('margin')
            }
        },

        // 保存全部
        saveAll () {
            showLoading()
            this.errorList = []
            Promise.all([
                this.basicInfoSave(),
                this.settlementSave(),
                this.marginSave()
            ])
                .then(() => {
                    hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(() => {
                    // this.clientPop('err', '保存失败', () => {
                    this.scorllError()
                    // })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 提交审核
        submitReview () {
            showLoading()
            this.errorList = []
            Promise.all([
                this.basicInfoSave(),
                this.settlementSave(),
                this.marginSave()
            ])
                .then(() => {
                    publics
                        .commitAudit(this.auditParams)
                        .then(() => {
                            this.clientPop('suc', '提交成功', this.handleClose)
                        })
                        .catch(() => {
                            // this.clientPop('err', '提交失败', () => {
                            this.scorllError()
                            // })
                        })
                })
                .catch(() => {
                    // this.clientPop('err', '提交失败', () => {
                    this.scorllError()
                    // })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 审核
        onAudit () {
            showLoading()
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                publics
                    .audit(auditParams)
                    .then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 撤销审核
        undoAudit () {
            showLoading()
            publics
                .undoAudit(this.auditParams)
                .then(() => {
                    this.clientPop('suc', '撤回成功', this.handleClose)
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                publics
                    .nullify(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 删除
        basicInfoDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                () => {
                    showLoading()
                    request
                        .basicInfoDelete(this.billid)
                        .then(() => {
                            this.clientPop('suc', '删除成功', this.handleClose)
                        })
                        .finally(() => {
                            hideLoading()
                        })
                }
            )
        },
        // 打印
        async print (value) {
            const printData = async ()=>{
                showLoading()
                try{
                    const  params =  {
                        'reportTitle': '', //报表名
                        'orgName': this.formData.orgName, //单据机构
                        'reportQRUri': '', //报表内容URI
                        'billNo': this.formData.billNo, //单据编码
                        'summaryInfoItems': [], // 基本信息
                        'tables': [] //表格
                    }
                    const reportTitle = this.commandList.find(item=>item.key == value)
                    params.reportTitle = reportTitle.value
                    const tableObj = {
                        1: this.Stmt(),
                        2: this.MarginPrn()
                    }
                    const tableData = tableObj[reportTitle.key]
                    params.summaryInfoItems = tableData.basicInfo
                    params.tables.push(tableData.tableList)
                    if(tableData.theScndTbl) {
                        params.tables.push(tableData.theScndTbl)
                    }
                    params.tables.push(await this.auditHst())
                    hideLoading()
                    return params
                }catch(err) {
                    console.log(err)
                    this.clientPop('err', '打印失败')
                    hideLoading()
                }
            }
            const data = await printData()
            webprintReport(data)
        },
        // 运输合同结算单
        Stmt () {
            const basicInfo = []
            const data = this.formData
            const list = [
                ['运输单位', data.settleOrgName, false],
                ['附件', '    ' + '张', false],
                ['结算依据', data.sourceNumber, false],
                ['发票编号', data.invoice, false],
                ['结算日期', data.billDate, false],
                ['本期结算合计', data.amountExcludingTax, false],
                ['税率(%)', data.taxRate + '%', false],
                ['可抵扣税额合计(元)', data.taxAmount, false],
                ['税价合计金额(元)', data.totalTaxPrice, false],
                ['累计结算金额', data.cumulativeSettleAmount, false],
                ['冲预付款金额', data.rushAdvanceChargePrice, false],
                ['税价合计金额大写', numToChinese(Math.abs(data.totalTaxPrice)), true],
                ['备注信息', data.remarks, true],
            ]
            list.forEach(item => {
                const obj = {
                    label: '标题',
                    value: '内容',
                    isFullRow: false, // 是否占整行
                }
                obj.label = item[0]
                obj.value = item[1]
                obj.isFullRow = item[2]
                basicInfo.push(obj)
            })
            // 表格数据
            const tableList = {
                'tableTitle': '结算明细',
                'tableContent': {
                    '名称': 'detailedName',
                    '计量单位': 'unit',
                    '出发地': 'departurePlace',
                    '目的地': 'destination',
                    '数量': 'amount',
                    '单价': 'price',
                    '金额': 'sum',
                },
                'tableData': this.settlementData, //表格数据
            }
            return { basicInfo, tableList }
        },
        // 保证金打印单
        MarginPrn () {
            const basicInfo = []
            const data = this.formData
            const list = [
                ['运输单位', data.settleOrgName, false],
                ['附件', '    ' + '张', false],
                ['结算依据', data.sourceNumber, false],
                ['发票编号', data.invoice, false],
                ['结算日期', data.billDate, false]
            ]
            list.forEach(item => {
                const obj = {
                    label: '标题',
                    value: '内容',
                    isFullRow: false, // 是否占整行
                }
                obj.label = item[0]
                obj.value = item[1]
                obj.isFullRow = item[2]
                basicInfo.push(obj)
            })
            // 暂扣保证金表格数据
            const tableList = {
                'tableTitle': '暂扣保证金',
                'tableContent': {
                    '名称': 'withholdBondName',
                    '暂扣保证金(元)': 'withholdBond',
                    '截止上期末暂扣保证金(元)': 'lastPeriodWithholdBond',
                    '说明': 'withholdExplain',
                },
                'tableData': this.$refs.marginRef.suspendedData, //表格数据
            }
            // 返还保证金表格数据
            const theScndTbl = {
                'tableTitle': '返还保证金',
                'tableContent': {
                    '名称': 'returnBondName',
                    '返还保证金(元)': 'returnBond',
                    '截止上期末未返还保证金(元)': 'notReturnBond',
                    '说明': 'returnExplain',
                },
                'tableData': this.$refs.marginRef.returnData, //表格数据
            }
            return { basicInfo, tableList, theScndTbl }
        },
        // 审核历史
        async auditHst () {
            //审核历史
            const historyList = {
                'tableTitle': '审核历史',
                'tableContent': {
                    '审核级次': 'unitName',
                    '审核人': 'assignUser',
                    '审核人岗位': 'userTitle',
                    '通知时间': 'notifyTime',
                    '审核时间': 'completeTime',
                    '审核意见': 'opinion',
                },
                'tableData': this.historyData, //表格数据
            }
            return historyList
        },
        // 点击冲红单
        redSingle () {
            this.$router.replace({
                path: '/contractOfCarriageSetAdd',
                query: { isRedSingle: '1', billid: this.billid }
            })
        },
        // ---------------------------下面按钮---------------------------
        // 获取按钮状态
        async getUnitInfo () {
            this.auditState = await publics.getCurrentUnitInfo(
                this.auditParams
            )
        },

        // 点击下面几个不同的按钮做不同的操作
        exas (arg) {
            if (arg === 'submit') {
                this.saveAll() // 保存所有数据
            } else if (arg === 'submitCommit') {
                this.submitReview() // 保存并提交
            } else if (arg === 'audit') {
                this.onAudit() // 审核
            } else if (arg === 'undoAudit') {
                this.undoAudit() // 撤销审核
            } else if (arg === 'nullify') {
                this.nullify() // 作废
            } else if (arg === 'deleteData') {
                this.basicInfoDelete() // 删除
            } else if(arg.type === 'multiple') {
                this.print(arg.value) // 打印
            }
        },

        //取消按钮
        handleClose () {
            this.$router.replace('/contractOfCarriageSetList')
        },

        // 公用
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (
                    document.getElementById('auditHistoryCon') &&
                    this.historyData.length > 0
                ) {
                    const lastConHeight =
                        document.getElementById('auditHistoryCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        historyTableHeight (data) {
            this.historyData = data
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        showState (state) {
            const _state = this.$store.state.equip.equipData.settleState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}
::v-deep.el-table .warning-row {
    display: none;
}
.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
.childTab {
    ::v-deep .el-tabs__header {
        position: absolute !important;
    }
    ::v-deep .el-tabs__content {
        padding: 0 0 0 20px !important;
    }
}
.childTab1 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: fixed;
                top: 0;
                width: 190px;
            }
        }
    }
}
.childTab2 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: absolute;
                bottom: 0;
                width: 100%;
            }
        }
    }
}
::v-deep .el-table__fixed{
        height: 100% !important
}
</style>
